package com.dps.omc.monitor;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.util.HashMap;
import java.util.Map;
import com.dps.omc.monitor.utils.MonitorConstants;

/**
 * Created by lip on 2016-05-30.
 */
public class MonitorServer {

    public void startUp()
    {
        // 启动JMX服务
        MBeanServer mbServer = MBeanServerFactory.createMBeanServer();
        String defaultDomain = mbServer.getDefaultDomain();
        MonitorService mybean = new MonitorService();
        ObjectName objectname = null;
        try {
            objectname = new ObjectName(defaultDomain + ":name=monitorService");
            mbServer.registerMBean(mybean, objectname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建一个jmx连接服务器

        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString();// 获得本机IP
            int port = MonitorConstants.PORT;
            LocateRegistry.createRegistry(port);
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + ip
                    + ":" + port + "/jndi/rmi://" + ip + ":" + port + "/server");
            System.out.println(url);
            Map<String, Object> map = new HashMap<String, Object>();
            JMXConnectorServer jmxConnectorServer = JMXConnectorServerFactory
                    .newJMXConnectorServer(url, map, mbServer);
            jmxConnectorServer.start();
            System.out.println("--------启动成功" + ip + "-------------");

        } catch (Exception e) {
            System.out.println("启动报错！");
            e.printStackTrace();
        }
    }
}
